package com.instpower.things.instpower;

import com.instpower.things.config.PropertyUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName InstppowerServer
 * @Author: hellmash@gmail.com
 * @Date: 2020/2/24
 * @Version: 1.0.0
 * @Description: TODO
 */
public class InstpowerServer {

    private final static Logger logger = LoggerFactory.getLogger("SYS");

    public void run() throws Exception {
        String port = PropertyUtil.getProperty("things.port", "9104");
        try {
            ServerBootstrap bootstrap = new ServerBootstrap().group(EventLoopGroupFactory.getBossGroup(),
                    EventLoopGroupFactory.getWorkerGroup())
                    .channel(NioServerSocketChannel.class)
                    //.option(ChannelOption.TCP_NODELAY, true)//tcp 发送是否需要延迟
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //.option(ChannelOption.SO_TIMEOUT, 1000)
                    //.option(ChannelOption.SO_KEEPALIVE, true)
                    //.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT) //tcp 接受和发送ByteBuffer是否使用动态扩容buf，默认就是AdaptiveRecvByteBufAllocator
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new InstpowerServerInitializer());
            //绑定端口
            bootstrap.bind(Integer.parseInt(port)).sync().channel().closeFuture().sync();
            logger.info("System start on {}",port);
        } finally {
            EventLoopGroupFactory.getBossGroup().shutdownGracefully();
            EventLoopGroupFactory.getWorkerGroup().shutdownGracefully();
        }

    }
}
